package com.annoncesautomobile.vue.rechercheAnnonce;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.annoncesautomobile.R;
import com.annoncesautomobile.modele.local.MesCoordonnes;
import com.annoncesautomobile.modele.util.ModelXML;
import com.annoncesautomobile.modele.util.Requete;
import com.annoncesautomobile.vue.SuperActivity;
import com.annoncesautomobile.vue.utils.ModalOk;

public class ChoixLoginActivity extends SuperActivity {

	private EditText login;
	private EditText password;
	private Requete request;
	private ProgressDialog progressDialog;


	protected void doRetour(String retour)
	{
		ModalOk.displayModalOk(ChoixLoginActivity.this, retour);
	}

	private class POSTRequete extends AsyncTask<Void, Void, Void>{
		private String adresse;
		private Requete request;
		private String retour;

		public POSTRequete(String adresse,Requete request,String keyFirstParam, String valueFirstParam)
		{
			this.adresse = adresse;
			this.request = request;
			this.request.put(keyFirstParam,valueFirstParam);
		}

		@Override
		protected void onPreExecute() {
			if(!progressDialog.isShowing()) {
				progressDialog.show();
			}
		}

		private String convertStreamToString(java.io.InputStream is) {
			java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
			return s.hasNext() ? s.next() : "";
		}

		protected void onPostExecute(Void p) {
			if(progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			doRetour(retour);
		}

		@Override
		protected Void doInBackground(Void...params ) {
			try
			{
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(adresse);
				MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();        
				multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
				Map<String,String> requestMapMode = this.request.getMapMode();
				for( Entry<String, String> aEntry : requestMapMode.entrySet())
				{
					if(aEntry.getKey().startsWith("file"))
					{
						multipartEntity.addPart("file", new FileBody(new File(aEntry.getValue())));
					}
					else
					{
						multipartEntity.addPart(aEntry.getKey(), new StringBody(aEntry.getValue(),ContentType.TEXT_PLAIN));
					}

				}
				post.setEntity(multipartEntity.build());
				HttpResponse response = client.execute(post);
				HttpEntity entity = response.getEntity();
				this.retour = convertStreamToString(entity.getContent());

			}
			catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}


	public final static boolean isValidEmail(CharSequence target) {
		if (target == null) {
			return false;
		} else {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
		}
	}
	private void mdpOublie()
	{
		String loginText = this.login.getText().toString();
		if(loginText == null || loginText.equals(""))
		{
			ModalOk.displayModalOk(ChoixLoginActivity.this, "Veuillez saisir votre email");
		}
		else
		{
			this.request.put("email", loginText);
			new POSTRequete(ModelXML.getAdresseMdpOublie(), request, "key", ModelXML.getKeyMdp()).execute();
		}
	}

	private void setIfAvailable(EditText ed , String nom)
	{
		String item = MesCoordonnes.getItemClient(ChoixLoginActivity.this, nom);
		if(item != null && !item.equals(""))
		{
			ed.setText(item);
		}
	}
	
	private void valider()
	{

		String loginText = this.login.getText().toString();
		String passwordText = this.password.getText().toString();
		String message = "Veuillez remplir tous les champs requis";
		boolean isOk = true;
		if(loginText != null && !loginText.equals("") )
		{
			if(isValidEmail(loginText))
			{
				this.request.put("email_conn", loginText);
			}
			else
			{
				message = "Votre adresse email est invalide";
				isOk = false;
			}
		}
		else
		{
			this.request.remove("email_conn");
		}

		if(passwordText != null && !passwordText.equals(""))
		{

			this.request.put("mdp_conn", md5(passwordText));
			//this.request.put("mdpbis_insc", passwordText);
		}
		else
		{
			this.request.remove("mdp_conn");
			//this.request.remove("mdpbis_insc");
		}
		this.request.remove("departement");
		this.request.remove("nom");
		this.request.remove("adresse");
		this.request.remove("cp");
		this.request.remove("ville");
		this.request.remove("tel1");
		this.request.remove("email_insc");
		this.request.remove("mdp_insc");
		this.request.remove("mdpbis_insc");

		if(this.request.get("mdp_conn") != null && this.request.get("email_conn") != null && isOk)
		{
			
			MesCoordonnes.setItemClient(ChoixLoginActivity.this,
					MesCoordonnes.PROPERTY_EMAIL_CLIENT,
					login.getText().toString());
			
			Intent output = new Intent();
			output.putExtra("requete", (Parcelable) request);
			setResult(RESULT_OK, output);
			finish();
		}
		else
		{
			ModalOk.displayModalOk(ChoixLoginActivity.this, message);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_choix_login);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar);
		TextView textViewActivityTitleText = (TextView) findViewById(R.id.activity_title_text);
		textViewActivityTitleText.setText(getString(R.string.title_activity_choix_login));

		addBoutonBas();
		
		this.login = (EditText) findViewById(R.id.editTextLogin);
		setIfAvailable(this.login, MesCoordonnes.PROPERTY_EMAIL_CLIENT);
		
		this.password = (EditText) findViewById(R.id.editTextPassword);
		this.request = (Requete) getIntent().getParcelableExtra("requete");
		this.progressDialog = new ProgressDialog(this);
		this.progressDialog.setMessage("Chargement...");
		Button b = (Button) findViewById(R.id.buttonValiderLogin);

		b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				valider();
			}
		});
		Button bMdpOublie = (Button) findViewById(R.id.buttonMdpOublie);
		bMdpOublie.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mdpOublie();
			}
		});
	}

	public void onBackPressed(View view) {
		this.onBackPressed();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	public String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}
	
	public static String md5(String string) {
	    byte[] hash;

	    try {
	        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
	    } catch (java.security.NoSuchAlgorithmException e) {
	        throw new RuntimeException("Huh, MD5 should be supported?", e);
	    } catch (UnsupportedEncodingException e) {
	        throw new RuntimeException("Huh, UTF-8 should be supported?", e);
	    }

	    StringBuilder hex = new StringBuilder(hash.length * 2);

	    for (byte b : hash) {
	        int i = (b & 0xFF);
	        if (i < 0x10) hex.append('0');
	        hex.append(Integer.toHexString(i));
	    }

	    return hex.toString();
	}
}
